import uuid

from django.conf import settings
from django.contrib.auth.models import AbstractUser
from django.db import models
from django.db.models.signals import post_save
from django.dispatch import receiver
from rest_framework.authtoken.models import Token

from Comicdb.settings import LANGUAGES
from utils.config.model_const import *
from utils.util_upload import author_upload_to, local_upload_to, chapter_upload_to, comic_upload_to, \
    recommend_upload_to, theme_upload_to, user_avatar_upload_to
# Create your models here.
from utils.util_uuid import get_5_16_number

READ_DIR_CHOICE = (
    (EnumComicReadDir.No.value, "無"),
    (EnumComicReadDir.RToL.value, "從右往左"),
    (EnumComicReadDir.LToR.value, "從左往右"),
    (EnumComicReadDir.TToB.value, "從上往下"),
)

VIP_CHOICE = (
    (EnumVipType.Normal.value, "普通會員"),
    (EnumVipType.Pay.value, "贊助會員"),
)

default_lang = "zh-hant"


@receiver(post_save, sender=settings.AUTH_USER_MODEL)
def create_auth_token(sender, instance=None, created=False, **kwargs):
    """
    创建token 后期改成redis
    :param sender:
    :param instance:
    :param created:
    :param kwargs:
    :return:
    """
    if created:
        Token.objects.create(user=instance)


class BaseModel(models.Model):
    """
    抽象类,继承对象可获得以下4个属性
    """
    b_deleted = models.BooleanField(verbose_name="是否删除",
                                    default=False)

    datetime_created = models.DateTimeField(verbose_name="创建时间",
                                            auto_now_add=True)
    # modifier = models.ForeignKey(User,
    #                              verbose_name="修改人",
    #                              on_delete=models.DO_NOTHING,
    #                              # limit_choices_to=~Q(manger_profile=None),
    #                              null=True,
    #                              blank=True)

    datetime_modifier = models.DateTimeField(verbose_name="修改时间",
                                             auto_now=True)

    class Meta:
        abstract = True

    def delete(self, using=None, keep_parents=False):
        self.b_deleted = True
        return self.save()


class BaseUUIDModel(BaseModel):
    """
    抽象类,uuid
    """
    # uuid 一般组成机器码 + 时间戳 * 100
    # uuid1() 基于MAC地址，时间戳，随机数来生成唯一的uuid，可以保证全球范围内的唯一性。
    uuid = models.UUIDField(verbose_name="uuid",
                            primary_key=True,
                            default=uuid.uuid1,
                            editable=False,
                            unique=True)

    class Meta:
        abstract = True


class User(AbstractUser):
    uuid = models.UUIDField(verbose_name="uuid",
                            default=uuid.uuid1,
                            primary_key=True)

    class Meta:
        verbose_name = "用户表"
        verbose_name_plural = "用户表"
        db_table = "user"


class UserInfo(BaseModel):
    """
    用户扩展表
    """

    GENDER_CHOICES = (
        (0, '不限'),
        (TagGenderType.Male.value, '男'),
        (TagGenderType.Female.value, '女'),
    )

    BLOOD_CHOICES = (
        (EnumUserBlood.A.value, 'A'),
        (EnumUserBlood.B.value, 'B'),
        (EnumUserBlood.AB.value, 'AB'),
        (EnumUserBlood.O.value, 'O'),
    )

    user = models.OneToOneField(User,
                                verbose_name="ID",
                                related_name="user_info_user",
                                primary_key=True,
                                on_delete=models.DO_NOTHING, )

    uuid = models.UUIDField(verbose_name="uuid",
                            default=uuid.uuid1,
                            editable=False,
                            unique=True)

    nickname = models.CharField(verbose_name="昵称",
                                max_length=50)

    avatar = models.ImageField(verbose_name="头像",
                               upload_to=user_avatar_upload_to,
                               max_length=512,
                               null=True,
                               blank=True, )

    gender = models.IntegerField(verbose_name="性别",
                                 choices=GENDER_CHOICES,
                                 default=0,
                                 blank=True,
                                 null=True)

    blood = models.CharField(verbose_name="血型",
                             choices=BLOOD_CHOICES,
                             max_length=10,
                             blank=True,
                             null=True)

    login_num = models.IntegerField(verbose_name="登录次数",
                                    default=0)
    login_last_ip = models.GenericIPAddressField(verbose_name="上一次登陆ip",
                                                 blank=True,
                                                 null=True)

    datetime_birthday = models.DateField(verbose_name="生日时间",
                                         null=True, )
    # 逻辑 每天更新redis里面所有用户信息 以会员等级为准
    # 逻辑： 1.查找vip_end空的 等级却有的  改掉
    #       2.查找时间不空但是时间少于单日0时的 改掉
    vip_level = models.IntegerField(verbose_name="会员等级",
                                    choices=VIP_CHOICE,
                                    default=EnumVipType.Normal.value)
    vip_end = models.DateTimeField(verbose_name="会员过期时间",
                                   help_text="显示和判断会员过期",
                                   null=True, )
    vip_start = models.DateTimeField(verbose_name="会员开始时间",
                                     help_text="显示",
                                     null=True, )

    # # 辅助属性
    b_verify_email = models.BooleanField(verbose_name="是否绑定邮箱",
                                         default=False)

    class Meta:
        verbose_name = "用户扩展表"
        verbose_name_plural = "用户扩展表"
        db_table = "user_info"

    def __str__(self):
        return "%s" % self.nickname


# class UserCollectComic(BaseUUIDModel):
#     """
#     用户漫画收藏
#     """
#
#     # user = models.ForeignKey(User,
#     #                          verbose_name="user_id",
#     #                          related_name="user_collect_comic_user",
#     #                          on_delete=models.DO_NOTHING, )
#
#     comic = models.ForeignKey("Comic",
#                               verbose_name="user_id",
#                               related_name="user_collect_comic_comic",
#                               on_delete=models.DO_NOTHING, )
#
#     class Meta:
#         verbose_name = "漫画收藏表"
#         verbose_name_plural = "漫画收藏表"
#         db_table = "user_collect_comic"
#
#
# class UserBrowseComic(BaseUUIDModel):
#     """
#     用户漫画浏览记录
#     """
#
#     # user = models.ForeignKey(User,
#     #                          verbose_name="user_id",
#     #                          related_name="user_collect_comic_user",
#     #                          on_delete=models.DO_NOTHING, )
#
#     comic = models.ForeignKey("Comic",
#                               verbose_name="user_id",
#                               related_name="user_collect_comic_comic",
#                               on_delete=models.DO_NOTHING, )
#
#     last_chapter = models.ForeignKey("Chapter",
#                                      verbose_name="最后阅读",
#                                      related_name="user_collect_comic_chapter",
#                                      on_delete=models.DO_NOTHING, )
#     last_chapter_name = models.CharField(verbose_name="名称",
#                                          null=True,
#                                          blank=True,
#                                          max_length=50)
#
#     class Meta:
#         verbose_name = "漫画浏览表"
#         verbose_name_plural = "漫画浏览表"
#         db_table = "user_browse_comic"


class Recommend(BaseUUIDModel):
    """
    推荐
    """
    TYPE_CHOICE = (
        (EnumRecommendType.Pics.value, "圖片推薦"),
        (EnumRecommendType.Comics.value, "漫畫推薦"),
        (EnumRecommendType.Words.value, "文字推薦"),
    )

    POS_CHOICE = (
        (EnumRecommendPos.WebPcHomeBanners.value, "PC_首页_Banner"),
        (EnumRecommendPos.WebPcHomeEditors.value, "PC_首页_编辑推荐"),
        (EnumRecommendPos.WebPcHomeWords.value, "PC_首页_文字推荐"),
        (EnumRecommendPos.WebPcFilterComics.value, "PC_筛选_漫画推荐"),
        (EnumRecommendPos.WebPcDetailComics.value, "PC_详情_漫画推荐"),
        (EnumRecommendPos.WebPcReadComics.value, "PC_阅读_漫画推荐"),
        (EnumRecommendPos.WebH5HomeBanners.value, "H5_首页_Banner"),
        (EnumRecommendPos.WebH5HomeEditors.value, "H5_首页_漫画推荐"),
        (EnumRecommendPos.WebH5SearchEditors.value, "H5_搜索_漫画推荐"),
    )

    title = models.CharField(verbose_name="标题",
                             max_length=200,
                             help_text="推荐语",
                             null=True,
                             blank=True)
    cover = models.ImageField(verbose_name="封面",
                              upload_to=recommend_upload_to,
                              max_length=512,
                              null=True,
                              blank=True, )
    pos = models.IntegerField(verbose_name="位置",
                              choices=POS_CHOICE,
                              null=True)
    type = models.IntegerField(verbose_name="内容类型",
                               choices=TYPE_CHOICE,
                               default=0)
    out_uuid = models.CharField(verbose_name="关联对象uuid",
                                max_length=150,
                                null=True,
                                blank=True)
    weight = models.IntegerField(verbose_name="权重",
                                 default=1)

    datetime_started = models.DateTimeField(verbose_name="开始时间")

    datetime_ended = models.DateTimeField(verbose_name="结束时间")

    brief = models.TextField(verbose_name="简述",
                             help_text="其他内容",
                             null=True,
                             blank=True)

    class Meta:
        verbose_name = "推荐"
        verbose_name_plural = "推荐"
        db_table = "recommend"

    def __str__(self):
        return "%s" % self.title


class Theme(BaseUUIDModel):
    """
    漫画-题材
    """
    INITIALS_CHOICE = (
        (0, "A"), (1, "B"), (2, "C"), (3, "D"), (4, "E"), (5, "F"), (6, "G"), (7, "H"), (8, "I"), (9, "J"), (10, "K"),
        (11, "L"), (12, "M"), (13, "N"), (14, "O"), (15, "P"), (16, "Q"), (17, "R"), (18, "S"), (19, "T"), (20, "U"),
        (21, "V"), (22, "W"), (23, "X"), (24, "Y"), (25, "Z"), (26, "0-9"),
    )

    name = models.CharField(verbose_name="名称",
                            max_length=20)
    initials = models.IntegerField(verbose_name="首字母",
                                   choices=INITIALS_CHOICE,
                                   default=0)
    path_word = models.CharField(verbose_name="路径关键词",
                                 max_length=100,
                                 unique=True)
    color_h5 = models.CharField(verbose_name="h5标签颜色",
                                max_length=7,
                                blank=True,
                                null=True)
    logo = models.ImageField(verbose_name="图标",
                             upload_to=theme_upload_to,
                             max_length=512,
                             null=True,
                             blank=True, )
    lang = models.CharField(verbose_name="语言",
                            choices=LANGUAGES,
                            default=default_lang,
                            max_length=10,
                            null=True,
                            blank=True)
    sort = models.IntegerField(verbose_name="排序",
                               help_text="越大,在前端越排在前",
                               default=0)

    class Meta:
        verbose_name = "漫画-题材"
        verbose_name_plural = "漫画-题材"
        db_table = "theme"

    def __str__(self):
        return (
                "%s - %s" % (self.get_initials_display(), self.name)
        ) if not self.b_deleted else (
                "%s - %s(%s)" % (self.get_initials_display(), self.name, "已删除")
        )

    def delete(self, using=None, keep_parents=False):
        self.b_deleted = True
        self.path_word = uuid.uuid1()
        return self.save()


class Tag(BaseUUIDModel):
    """
    漫画-题材
    """
    GENDER_CHOICES = (
        (0, '不限'),
        (TagGenderType.Male.value, '男'),
        (TagGenderType.Female.value, '女'),
    )

    INITIALS_CHOICE = (
        (0, "A"), (1, "B"), (2, "C"), (3, "D"), (4, "E"), (5, "F"), (6, "G"), (7, "H"), (8, "I"), (9, "J"), (10, "K"),
        (11, "L"), (12, "M"), (13, "N"), (14, "O"), (15, "P"), (16, "Q"), (17, "R"), (18, "S"), (19, "T"), (20, "U"),
        (21, "V"), (22, "W"), (23, "X"), (24, "Y"), (25, "Z"), (26, "0-9"),
    )

    name = models.CharField(verbose_name="名称",
                            max_length=20)
    initials = models.IntegerField(verbose_name="首字母",
                                   choices=INITIALS_CHOICE,
                                   default=0)
    path_word = models.CharField(verbose_name="路径关键词",
                                 max_length=100,
                                 unique=True)
    gender = models.IntegerField(verbose_name="性别",
                                 choices=GENDER_CHOICES,
                                 default=0,
                                 blank=True,
                                 null=True)
    color_h5 = models.CharField(verbose_name="h5标签颜色",
                                max_length=7,
                                blank=True,
                                null=True)
    logo = models.ImageField(verbose_name="图标",
                             upload_to=theme_upload_to,
                             max_length=512,
                             null=True,
                             blank=True, )
    lang = models.CharField(verbose_name="语言",
                            choices=LANGUAGES,
                            default=default_lang,
                            max_length=10,
                            null=True,
                            blank=True)
    sort = models.IntegerField(verbose_name="排序",
                               help_text="越大,在前端越排在前",
                               default=0)

    class Meta:
        verbose_name = "漫画-标签"
        verbose_name_plural = "漫画-标签"
        db_table = "tag"

    def __str__(self):
        return (
                "%s - %s" % (self.get_initials_display(), self.name)
        ) if not self.b_deleted else (
                "%s - %s(%s)" % (self.get_initials_display(), self.name, "已删除")
        )

    def delete(self, using=None, keep_parents=False):
        self.b_deleted = True
        self.path_word = uuid.uuid1()
        return self.save()


class Parody(BaseUUIDModel):
    """
    同人志-原作品
    """
    INITIALS_CHOICE = (
        (0, "A"), (1, "B"), (2, "C"), (3, "D"), (4, "E"), (5, "F"), (6, "G"), (7, "H"), (8, "I"), (9, "J"), (10, "K"),
        (11, "L"), (12, "M"), (13, "N"), (14, "O"), (15, "P"), (16, "Q"), (17, "R"), (18, "S"), (19, "T"), (20, "U"),
        (21, "V"), (22, "W"), (23, "X"), (24, "Y"), (25, "Z"), (26, "0-9"),
    )
    name = models.CharField(verbose_name="名称",
                            max_length=100)
    trans_name = models.CharField(verbose_name="英文",
                                  max_length=100,
                                  null=True,
                                  blank=True)
    initials = models.IntegerField(verbose_name="首字母",
                                   choices=INITIALS_CHOICE,
                                   default=0)
    path_word = models.CharField(verbose_name="路径关键词",
                                 max_length=100,
                                 unique=True)
    sort = models.IntegerField(verbose_name="排序",
                               help_text="越大,在前端越排在前",
                               default=0)

    class Meta:
        verbose_name = "同人志-原作品"
        verbose_name_plural = "同人志-原作品"
        db_table = "parody"

    def __str__(self):
        return (
                "%s - %s" % (self.get_initials_display(), self.name)
        ) if not self.b_deleted else (
                "%s - %s(%s)" % (self.get_initials_display(), self.name, "已删除")
        )

    def delete(self, using=None, keep_parents=False):
        self.b_deleted = True
        self.path_word = uuid.uuid1()
        return self.save()


# 严格限制
NORMAL_RESTRICT = [
    EnumComicRestrict.Normal.value,
]

R16_RESTRICT = [
    EnumComicRestrict.Sensitive.value,
    EnumComicRestrict.Bare.value,
]

R18_RESTRICT = [
    EnumComicRestrict.Erotic.value,
    EnumComicRestrict.Bloody.value,
]


class Comic(BaseUUIDModel):
    """
    漫画
    """
    RESTRICT_CHOICE = (
        (EnumComicRestrict.Normal.value, "一般向"),
        (EnumComicRestrict.Sensitive.value, "擦邊級"),
        (EnumComicRestrict.Bare.value, "裸露級"),
        (EnumComicRestrict.Erotic.value, "情色級"),
        (EnumComicRestrict.Bloody.value, "血腥級")
    )
    LEVEL_CHOICE = (
        (EnumComicLevel.High.value, "精品"),
        (EnumComicLevel.Normal.value, "一般"),
        (EnumComicLevel.Rubbish.value, "垃圾"),
    )
    RECLASS_CHOICE = (
        (EnumComicReClass.Manga.value, "漫畫Manga"),
        (EnumComicReClass.Doujinshi.value, "同人志Doujinshi"),
    )
    CO_CHOICE = (
        (EnumComicCo.Not_Copyright.value, "無版權"),
        (EnumComicCo.Copyright.value, "有版權"),
        (EnumComicCo.Torts.value, "已侵權"),
        (EnumComicCo.App_Torts.value, "App侵權")
    )
    REGION_CHOICE = (
        (EnumComicRegion.Japan.value, "日本"),
        (EnumComicRegion.Korea.value, "韓國"),
        (EnumComicRegion.West.value, "歐美"),
        (EnumComicRegion.HK.value, "港台"),
        (EnumComicRegion.Inland.value, "內地"),
        (EnumComicRegion.Other.value, "其他"),
    )
    STATUS_CHOICE = (
        (EnumComicStatus.Serializing.value, "連載中"),
        (EnumComicStatus.Finished.value, "已完結"),
        (EnumComicStatus.Short.value, "短篇"),
    )
    AUDIENCE_CHOICE = (
        (EnumComicAudience.Boy.value, "少年漫畫"),
        (EnumComicAudience.Girl.value, "少女漫畫"),
        (EnumComicAudience.Male.value, "青年漫畫"),
        (EnumComicAudience.Female.value, "女青漫畫"),
    )

    INITIALS_CHOICE = (
        (0, "A"), (1, "B"), (2, "C"), (3, "D"), (4, "E"), (5, "F"), (6, "G"), (7, "H"), (8, "I"), (9, "J"), (10, "K"),
        (11, "L"), (12, "M"), (13, "N"), (14, "O"), (15, "P"), (16, "Q"), (17, "R"), (18, "S"), (19, "T"), (20, "U"),
        (21, "V"), (22, "W"), (23, "X"), (24, "Y"), (25, "Z"), (26, "0-9"),
    )

    name = models.CharField(verbose_name="名称",
                            max_length=200)
    alias = models.CharField(verbose_name="别名",
                             help_text=",分隔",
                             max_length=200,
                             null=True,
                             blank=True)
    orig_name = models.CharField(verbose_name="原名",
                                 max_length=200,
                                 null=True,
                                 blank=True)
    role = models.CharField(verbose_name="角色",
                            help_text=",号分隔，帮助搜索",
                            max_length=200,
                            null=True,
                            blank=True,
                            )
    path_word = models.CharField(verbose_name="路径关键词",
                                 max_length=100,
                                 unique=True
                                 )
    initials = models.IntegerField(verbose_name="首字母",
                                   choices=INITIALS_CHOICE,
                                   default=0)
    b_404 = models.BooleanField(verbose_name="404",
                                default=False)
    b_hidden = models.BooleanField(verbose_name="隐藏",
                                   default=False)
    cover = models.ImageField(verbose_name="封面",
                              upload_to=comic_upload_to,
                              max_length=512,
                              null=True,
                              blank=True, )
    reclass = models.IntegerField(verbose_name="ehentai分类",
                                  choices=RECLASS_CHOICE,
                                  default=1)
    read_dir = models.IntegerField(verbose_name="阅读方向",
                                   choices=READ_DIR_CHOICE,
                                   default=0)
    restrict = models.IntegerField(verbose_name="限制级",
                                   choices=RESTRICT_CHOICE,
                                   default=0)
    level = models.IntegerField(verbose_name="等级",
                                choices=LEVEL_CHOICE,
                                default=1)
    co = models.IntegerField(verbose_name="版权",
                             choices=CO_CHOICE,
                             default=0)
    lang = models.CharField(verbose_name="语言",
                            choices=LANGUAGES,
                            default=default_lang,
                            max_length=10,
                            null=True,
                            blank=True)
    region = models.IntegerField(verbose_name="地域",
                                 choices=REGION_CHOICE,
                                 default=5)
    status = models.IntegerField(verbose_name="状态",
                                 choices=STATUS_CHOICE,
                                 default=0)
    audience = models.IntegerField(verbose_name="受众",
                                   choices=AUDIENCE_CHOICE,
                                   default=0)
    author = models.ManyToManyField("Author",
                                    verbose_name="作者",
                                    related_name="comic_author",
                                    blank=True)
    parodies = models.ManyToManyField("Parody",
                                      verbose_name="同人志原作品",
                                      related_name="comic_parody",
                                      blank=True)
    clubs = models.ManyToManyField("Club",
                                   verbose_name="社团",
                                   related_name="comic_club",
                                   blank=True)
    theme = models.ManyToManyField("Theme",
                                   verbose_name="题材",
                                   related_name="comic_theme",
                                   blank=True)
    females = models.ManyToManyField("Tag",
                                     verbose_name="女性题材",
                                     related_name="comic_female_tag",
                                     blank=True)
    males = models.ManyToManyField("Tag",
                                   verbose_name="男性题材",
                                   related_name="comic_male_tag",
                                   blank=True)
    misc = models.CharField(verbose_name="其他",
                            max_length=128,
                            null=True,
                            blank=True)
    brief = models.TextField(verbose_name="简介",
                             null=True,
                             blank=True)
    popular = models.BigIntegerField(verbose_name="人气",
                                     help_text="点击数",
                                     default=0)
    datetime_publish = models.DateTimeField(verbose_name="发行时间",
                                            null=True,
                                            blank=True)
    datetime_updated = models.DateTimeField(verbose_name="最后更新时间",
                                            null=True,
                                            blank=True)
    last_chapter = models.ForeignKey("Chapter",
                                     verbose_name="最后更新一话",
                                     related_name="comic_last_chapter",
                                     on_delete=models.DO_NOTHING,
                                     null=True,
                                     blank=True)

    class Meta:
        verbose_name = "漫画"
        verbose_name_plural = "漫画"
        db_table = "comic"
        ordering = ("-datetime_created",)

    def __str__(self):
        return "%s" % self.name

    def delete(self, using=None, keep_parents=False):
        self.b_deleted = True
        self.path_word = uuid.uuid1()
        return self.save()

    @staticmethod
    def autocomplete_search_fields():
        return 'name', 'alias'


class ComicRecord(BaseUUIDModel):
    """
    漫画-记录（用于记录用户和漫画相关的行为）
    """
    user = models.OneToOneField(User,
                                verbose_name="用户",
                                related_name="comic_record_user",
                                on_delete=models.DO_NOTHING)
    comic = models.OneToOneField("Comic",
                                 verbose_name="漫画",
                                 related_name="comic_record_comic",
                                 on_delete=models.DO_NOTHING)

    support = models.BooleanField(verbose_name="顶",
                                  default=False)

    trample = models.BooleanField(verbose_name="踩",
                                  default=False)

    score = models.IntegerField(verbose_name="评分",
                                default=0)

    class Meta:
        verbose_name = "漫画-记录"
        verbose_name_plural = "漫画-记录"
        db_table = "comic_record"

    def __str__(self):
        return "%s" % self.user.username


class ComicComment(BaseUUIDModel):
    """
    漫画-评论
    """
    user = models.ForeignKey(User,
                             verbose_name="用户",
                             related_name="comic_comment_user",
                             on_delete=models.DO_NOTHING)

    comic = models.ForeignKey("Comic",
                              verbose_name="漫画",
                              related_name="comic_comment_comic",
                              on_delete=models.DO_NOTHING)

    report = models.ForeignKey("ComicComment",
                               verbose_name="反馈",
                               related_name="comic_comment_report",
                               on_delete=models.DO_NOTHING)

    username = models.CharField(verbose_name="用户名",
                                max_length=20)

    support = models.IntegerField(verbose_name="顶",
                                  default=0)

    class Meta:
        verbose_name = "漫画-评论"
        verbose_name_plural = "漫画-评论"
        db_table = "comic_comment"

    def __str__(self):
        return "%s" % self.comic.name


class ComicCommentCount(BaseUUIDModel):
    """
    漫画-评论-统计
    """
    user = models.ForeignKey(User,
                             verbose_name="用户",
                             related_name="comic_comment_count_user",
                             on_delete=models.DO_NOTHING)

    comment = models.ForeignKey("ComicComment",
                                verbose_name="漫画",
                                related_name="comic_comment_count_comment",
                                on_delete=models.DO_NOTHING)

    support = models.BooleanField(verbose_name="顶",
                                  default=False)

    class Meta:
        verbose_name = "漫画-评论-统计"
        verbose_name_plural = "漫画-评论-统计"
        db_table = "comic_comment_count"

    def __str__(self):
        return "%s" % self.comment.comic.name


class ComicCommentReport(BaseUUIDModel):
    """
    漫画-评论-反馈（举报）
    """
    user = models.ForeignKey(User,
                             verbose_name="用户",
                             related_name="comic_comment_report_user",
                             on_delete=models.DO_NOTHING)

    comment = models.ForeignKey("ComicComment",
                                verbose_name="评论",
                                related_name="comic_comment_report_comment",
                                on_delete=models.DO_NOTHING)

    class Meta:
        verbose_name = "漫画-评论-反馈"
        verbose_name_plural = "漫画-评论-反馈"
        db_table = "comic_comment_report"

    def __str__(self):
        return "%s" % self.comment.comic.name


class ComicCount(models.Model):
    comic = models.OneToOneField("Comic",
                                 verbose_name="漫画本",
                                 related_name="comic_count_comic",
                                 primary_key=True,
                                 on_delete=models.DO_NOTHING)

    popular = models.BigIntegerField(verbose_name="人气",
                                     help_text="点击数",
                                     default=0)

    class Meta:
        verbose_name = "漫画人气"
        verbose_name_plural = "漫画人气"
        db_table = "comic_count"

    def __str__(self):
        return r"%s-人气:%s" % (self.comic.name, str(self.popular))


class ComicRankRecord(BaseUUIDModel):
    """
    排行记录 每天统计类
    """
    comic = models.ForeignKey("Comic",
                              verbose_name="漫画本",
                              related_name="comic_rank_record_comic",
                              on_delete=models.CASCADE)
    popular = models.BigIntegerField(verbose_name="人气",
                                     help_text="点击数",
                                     default=0)
    last_popular = models.BigIntegerField(verbose_name="上一次人气",
                                          default=0)
    rise_num = models.BigIntegerField(verbose_name="上升数量",
                                      default=0)
    datetime_update = models.DateTimeField(verbose_name="更新时间",
                                           null=True)

    class Meta:
        verbose_name = "漫画排行记录"
        verbose_name_plural = "漫画排行记录"
        db_table = "comic_rank_record"

    def __str__(self):
        return r"%s-昨日上升:%s" % (self.comic.name, str(self.rise_num))


class ComicRankTemporary(models.Model):
    """
    排行记录 每天统计类 临时表 条数过于巨大 每天排好删除 取前1000条
    """
    comic = models.ForeignKey("Comic",
                              verbose_name="漫画本",
                              related_name="comic_rank_temporary_comic",
                              on_delete=models.CASCADE)
    popular = models.BigIntegerField(verbose_name="人气",
                                     help_text="点击数",
                                     default=0)
    last_popular = models.BigIntegerField(verbose_name="上一次人气",
                                          default=0)
    rise_num = models.BigIntegerField(verbose_name="上升数量",
                                      default=0)

    datetime_update = models.DateTimeField(verbose_name="更新时间",
                                           null=True)
    datetime_created = models.DateTimeField(verbose_name="创建时间",
                                            auto_now_add=True)

    class Meta:
        verbose_name = "漫画排行记录临时"
        verbose_name_plural = "漫画排行记录临时"
        db_table = "comic_rank_temporary"

    def __str__(self):
        return r"%s-昨日上升:%s" % (self.comic.name, str(self.rise_num))


class ComicUpdateRecord(BaseUUIDModel):
    """
    漫画更新
    """
    comic = models.ForeignKey("Comic",
                              verbose_name="漫画本",
                              related_name="comic_update_record_comic",
                              on_delete=models.CASCADE)

    chapter = models.ForeignKey("Chapter",
                                help_text="最后更新章节",
                                verbose_name="章节",
                                related_name="comic_update_record_chapter",
                                on_delete=models.CASCADE)

    class Meta:
        verbose_name = "漫画更新记录"
        verbose_name_plural = "漫画更新记录"
        db_table = "comic_update_record"

    def __str__(self):
        return r"%s-更新时间:%s" % (self.comic.name, str(self.datetime_created))


class Chapter(BaseUUIDModel):
    """
    漫画-章节
    """
    TYPE_CHOICE = (
        (EnumChapterType.Not_Set.value, "未設置"),
        (EnumChapterType.Words.value, "話"),
        (EnumChapterType.Roll.value, "卷"),
        (EnumChapterType.Extra.value, "番外篇"),
    )

    SOURCE_CHOICE = (
        (EnumChapterSource.Reprint.value, "轉載"),
        (EnumChapterSource.Fan.value, "同人"),
        (EnumChapterSource.Original.value, "原創"),
        (EnumChapterSource.Authorise.value, "授權"),
        (EnumChapterSource.Exclusive.value, "獨家合作"),
        (EnumChapterSource.First.value, "首發"),
    )

    comic = models.ForeignKey("Comic",
                              verbose_name="漫画本",
                              related_name="chapter_comic",
                              on_delete=models.DO_NOTHING)
    serial = models.CharField(verbose_name="序号",
                              help_text="存贮漫画文件夹, 4, 16位",
                              max_length=10,
                              default=get_5_16_number,
                              editable=False)
    name = models.CharField(verbose_name="名称",
                            max_length=50)
    sort = models.DecimalField(verbose_name="序号",
                               decimal_places=2,
                               max_digits=10)
    ordered = models.IntegerField(verbose_name="排序",
                                  help_text="排序字段",
                                  default=0)
    lang = models.CharField(verbose_name="语言",
                            choices=LANGUAGES,
                            default=default_lang,
                            max_length=10,
                            null=True,
                            blank=True)
    source = models.IntegerField(verbose_name="来源",
                                 choices=SOURCE_CHOICE,
                                 default=0)
    type = models.IntegerField(verbose_name="类型",
                               choices=TYPE_CHOICE,
                               default=1)
    group = models.ForeignKey("ChapterGroup",
                              verbose_name="分组",
                              on_delete=models.DO_NOTHING,
                              related_name="chapter_chapter_group",
                              null=True,
                              blank=True)
    local = models.ManyToManyField("LocalGroup",
                                   verbose_name="汉化组",
                                   related_name="chapter_local",
                                   blank=True)
    bulk_url = models.CharField(verbose_name="批量上转路径",
                                max_length=500,
                                null=True,
                                blank=True)
    outer_url = models.CharField(verbose_name="外链URL",
                                 max_length=500,
                                 null=True,
                                 blank=True)
    read_dir = models.IntegerField(verbose_name="阅读方向",
                                   choices=READ_DIR_CHOICE,
                                   default=0)
    b_display = models.BooleanField(verbose_name="是否显示",
                                    default=True)
    count = models.IntegerField(verbose_name="内容数量",
                                default=0)

    class Meta:
        verbose_name = "章节"
        verbose_name_plural = "章节"
        db_table = "chapter"
        ordering = ('group', 'ordered', 'sort',)

    def __str__(self):
        return "%s-%s-%s-%s" % (
            self.group.name[:2] if self.group is not None else "默认",
            self.sort,
            self.ordered,
            self.name[:3])

    def delete(self, using=None, keep_parents=False):
        self.b_deleted = True
        self.sort = 0
        self.ordered = 0
        return self.save()


class ChapterGroup(BaseUUIDModel):
    """
    漫画-章节-分组
    """
    name = models.CharField(verbose_name="名称",
                            max_length=50)
    lang = models.CharField(verbose_name="语言",
                            choices=LANGUAGES,
                            default=default_lang,
                            max_length=10,
                            null=True,
                            blank=True)
    sort = models.IntegerField(verbose_name="排序",
                               default=0)

    class Meta:
        verbose_name = "章节-分组"
        verbose_name_plural = "章节-分组"
        db_table = "chapter_group"

    def __str__(self):
        return ("%s" % self.name) if not self.b_deleted else ("%s(%s)" % (self.name, "已删除"))


class ChapterContent(BaseUUIDModel):
    """
    章节-内容
    """
    RATIO_CHOICE = (
        (EnumContentSource.HIGH.value, "高圖"),
        (EnumContentSource.WIDTH.value, "寬圖")
    )

    chapter = models.ForeignKey("Chapter",
                                verbose_name="章节",
                                on_delete=models.DO_NOTHING,
                                related_name="chapter_content_chapter")
    name = models.CharField(verbose_name="名称",
                            max_length=200)
    url = models.ImageField(verbose_name="地址",
                            upload_to=chapter_upload_to,
                            max_length=512,
                            null=True,
                            blank=True, )
    ratio = models.IntegerField(verbose_name="比例类型",
                                choices=RATIO_CHOICE,
                                default=10)
    size = models.BigIntegerField(verbose_name="大小",
                                  default=0)
    width = models.IntegerField(verbose_name="宽",
                                default=0)
    height = models.IntegerField(verbose_name="高",
                                 default=0)
    sort = models.IntegerField(verbose_name="排序",
                               default=10000)

    class Meta:
        verbose_name = "章节-内容"
        verbose_name_plural = "章节-内容"
        db_table = "chapter_content"
        ordering = ("sort",)

    def __str__(self):
        return "%s" % self.name


class Author(BaseUUIDModel):
    """
    作者
    """
    name = models.CharField(verbose_name="名称",
                            max_length=50)
    alias = models.CharField(verbose_name="别名",
                             help_text=",分隔",
                             max_length=200,
                             null=True,
                             blank=True)
    path_word = models.CharField(verbose_name="路径关键词",
                                 max_length=100,
                                 unique=True)
    avatar = models.ImageField(verbose_name="头像地址",
                               upload_to=author_upload_to,
                               max_length=512,
                               null=True,
                               blank=True, )
    brief = models.TextField(verbose_name="简介",
                             null=True,
                             blank=True)

    class Meta:
        verbose_name = "作者"
        verbose_name_plural = "作者"
        db_table = "author"

    def __str__(self):
        return ("%s" % self.name) if not self.b_deleted else ("%s(%s)" % (self.name, "已删除"))

    def delete(self, using=None, keep_parents=False):
        self.b_deleted = True
        self.path_word = uuid.uuid1()
        return self.save()

    @staticmethod
    def autocomplete_search_fields():
        return 'name', 'alias'


class Club(BaseUUIDModel):
    """
    社团
    """
    name = models.CharField(verbose_name="名称",
                            max_length=50)
    alias = models.CharField(verbose_name="别名",
                             help_text=",分隔",
                             max_length=200,
                             null=True,
                             blank=True)
    path_word = models.CharField(verbose_name="路径关键词",
                                 max_length=100,
                                 unique=True)
    avatar = models.ImageField(verbose_name="头像地址",
                               upload_to=author_upload_to,
                               max_length=512,
                               null=True,
                               blank=True, )
    brief = models.TextField(verbose_name="简介",
                             null=True,
                             blank=True)

    class Meta:
        verbose_name = "社团"
        verbose_name_plural = "社团"
        db_table = "club"

    def __str__(self):
        return ("%s" % self.name) if not self.b_deleted else ("%s(%s)" % (self.name, "已删除"))

    def delete(self, using=None, keep_parents=False):
        self.b_deleted = True
        self.path_word = uuid.uuid1()
        return self.save()


class LocalGroup(BaseUUIDModel):
    """
    漫画-汉化组
    """
    name = models.CharField(verbose_name="名称",
                            max_length=200,
                            unique=True)
    alias = models.CharField(verbose_name="别名",
                             help_text=",分隔",
                             max_length=200,
                             null=True,
                             blank=True)
    leader = models.CharField(verbose_name="组长名称",
                              max_length=200,
                              null=True,
                              blank=True)
    path_word = models.CharField(verbose_name="路径关键词",
                                 max_length=100,
                                 unique=True)
    logo = models.ImageField(verbose_name="logo",
                             upload_to=local_upload_to,
                             max_length=512,
                             null=True,
                             blank=True, )
    website = models.CharField(verbose_name="官网",
                               help_text=",分隔",
                               max_length=1000,
                               null=True,
                               blank=True
                               )
    weibo = models.CharField(verbose_name="微博",
                             help_text=",分隔",
                             max_length=1000,
                             null=True,
                             blank=True
                             )
    email = models.CharField(verbose_name="邮箱",
                             help_text=",分隔",
                             max_length=1000,
                             null=True,
                             blank=True
                             )
    brief = models.TextField(verbose_name="简介",
                             null=True,
                             blank=True)

    class Meta:
        verbose_name = "汉化组"
        verbose_name_plural = "汉化组"
        db_table = "local_group"

    def __str__(self):
        return ("%s" % self.name) if not self.b_deleted else ("%s(%s)" % (self.name, "已删除"))

    def delete(self, using=None, keep_parents=False):
        self.b_deleted = True
        self.path_word = uuid.uuid1()
        return self.save()


class DataComic(models.Model):
    """
    漫画
    """
    uuid = models.CharField(verbose_name="uuid",
                            max_length=50)
    id = models.IntegerField(verbose_name="id",
                             primary_key=True,
                             )
    name = models.CharField(verbose_name="名称",
                            max_length=200,
                            null=True,
                            blank=True
                            )
    short_name = models.CharField(verbose_name="名称",
                                  max_length=200,
                                  null=True,
                                  blank=True
                                  )
    comic_url = models.CharField(verbose_name="名称",
                                 max_length=200,
                                 null=True,
                                 blank=True
                                 )
    alias = models.CharField(verbose_name="别名",
                             help_text=",分隔",
                             max_length=200,
                             null=True,
                             blank=True)
    orig_name = models.CharField(verbose_name="原名",
                                 max_length=200,
                                 null=True,
                                 blank=True)
    path_word = models.CharField(verbose_name="路径关键词",
                                 max_length=100,
                                 unique=True
                                 )
    status = models.IntegerField(verbose_name="状态",
                                 default=0)

    cover_spy = models.CharField(verbose_name="封面",
                                 max_length=200,
                                 null=True,
                                 blank=True)
    cover_local_path = models.CharField(verbose_name="封面",
                                        max_length=200,
                                        null=True,
                                        blank=True)
    cover = models.CharField(verbose_name="封面",
                             max_length=500,
                             null=True,
                             blank=True)
    author_spy = models.CharField(verbose_name="作者",
                                  max_length=500,
                                  null=True,
                                  blank=True, )
    author_link_tag_spy = models.CharField(verbose_name="作者",
                                           max_length=500,
                                           null=True,
                                           blank=True, )
    initials_spy = models.CharField(verbose_name="首字母",
                                    max_length=50,
                                    null=True,
                                    blank=True
                                    )
    initials = models.IntegerField(verbose_name="首字母",
                                   default=-1)
    region_spy = models.CharField(verbose_name="地域",
                                  max_length=50,
                                  null=True,
                                  blank=True
                                  )
    region = models.IntegerField(verbose_name="地域",
                                 default=5)

    audience_spy = models.CharField(verbose_name="受众",
                                    max_length=50,
                                    null=True,
                                    blank=True
                                    )
    audience = models.CharField(verbose_name="受众",
                                max_length=50,
                                null=True,
                                blank=True
                                )
    theme_spy = models.CharField(verbose_name="题材",
                                 max_length=50,
                                 null=True,
                                 blank=True
                                 )

    detail_link = models.CharField(verbose_name="链接",
                                   max_length=500,
                                   null=True,
                                   blank=True
                                   )
    brief = models.TextField(verbose_name="简介",
                             null=True,
                             blank=True)

    class Meta:
        verbose_name = "漫画数据"
        verbose_name_plural = "漫画数据"
        db_table = "data_comic"


class Goods(BaseUUIDModel):
    """
    商品
    """
    name = models.CharField(verbose_name="商品名称",
                            max_length=50)
    vip_level = models.IntegerField(verbose_name="购买会员等级",
                                    choices=VIP_CHOICE,
                                    default=EnumVipType.Pay.value)
    num = models.IntegerField(verbose_name="长度",
                              default=1)
    price_orig = models.DecimalField(verbose_name="原价",
                                     max_digits=10,
                                     decimal_places=2,
                                     default=0,
                                     )
    price = models.DecimalField(verbose_name="价格",
                                max_digits=10,
                                decimal_places=2,
                                default=0,
                                )

    class Meta:
        verbose_name = "vip-商品"
        verbose_name_plural = "vip-商品"
        db_table = "goods"

    def __str__(self):
        return self.name

    def delete(self, using=None, keep_parents=False):
        self.b_deleted = True
        return self.save()


class OrderRecord(BaseUUIDModel):
    """
    订单详情
    """
    STATUS_CHOICE = (
        (EnumOrderStatus.Unpaid.value, "未支付"),
        (EnumOrderStatus.Paid.value, "已支付"),
        (EnumOrderStatus.Error.value, "支付失敗")
    )
    PLATFORM_CHOICE = (
        (EnumOrderPayPlatform.Other.value, "暂时其他平台"),
        (EnumOrderPayPlatform.AliPay.value, "支付宝"),
        (EnumOrderPayPlatform.WX.value, "微信")
    )

    user = models.ForeignKey(User,
                             verbose_name="用户",
                             on_delete=models.DO_NOTHING,
                             related_name="order_record_user")
    goods = models.ForeignKey("Goods",
                              verbose_name="商品",
                              on_delete=models.DO_NOTHING,
                              related_name="order_record_goods")
    title = models.CharField(verbose_name="订单标题",
                             max_length=50)
    no = models.CharField(verbose_name="订单编号",
                          max_length=50,
                          unique=True)
    goods_name = models.CharField(verbose_name="商品名称",
                                  max_length=50)
    goods_num = models.IntegerField(verbose_name="商品数量",
                                    default=1)
    status = models.IntegerField(verbose_name="订单状态",
                                 choices=STATUS_CHOICE,
                                 default=EnumOrderStatus.Unpaid.value)
    platform = models.IntegerField(verbose_name="支付方式",
                                   choices=PLATFORM_CHOICE,
                                   default=EnumOrderPayPlatform.Other.value
                                   )
    price_total = models.DecimalField(verbose_name="总价",
                                      max_digits=10,
                                      decimal_places=2,
                                      default=0,
                                      )
    price_pay = models.DecimalField(verbose_name="支付价格",
                                    max_digits=10,
                                    decimal_places=2,
                                    default=0,
                                    )
    price_bill = models.DecimalField(verbose_name="支付进账",
                                     max_digits=10,
                                     decimal_places=2,
                                     default=0,
                                     )
    datetime_pay = models.DateTimeField(verbose_name="支付时间",
                                        null=True)
    datetime_vip_start = models.DateTimeField(verbose_name="vip开始时间",
                                              null=True)
    datetime_vip_end = models.DateTimeField(verbose_name="vip结束时间",
                                            null=True)
    remark = models.CharField(verbose_name="备注",
                              max_length=1000,
                              null=True,
                              blank=True)

    class Meta:
        verbose_name = "订单"
        verbose_name_plural = "订单"
        db_table = "order_record"

    def __str__(self):
        return self.title

    def delete(self, using=None, keep_parents=False):
        self.b_deleted = True
        return self.save()


@receiver(post_save, sender=Chapter)
def callback_chapter_save(sender, **kwargs):
    """
    只有在后台提交修改  {
            更新cache
            分组刷新
            章节刷新
    }
    这里只是把记录刷下
    :param sender:
    :param kwargs:
    :return:
    """
    _obj = kwargs.get('instance') or None
    if not _obj:
        return
    # 初次创建count
    created = kwargs.get('created') or False
    if created:
        ComicUpdateRecord.objects.create(
            comic_id=_obj.comic_id,
            chapter_id=_obj.uuid
        )


class UserObject(object):
    """
    用于登陆之后的user_id
    """
    is_authenticated = False
    nickname = None
    user_id = None
    uuid = None
    vip_level = 0

    def __init__(self, **attr):
        self.__dict__.update(attr)
